package com.wswy.wzcx.ui.main.home;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.OnScrollListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import com.che.libcommon.api.page.Pagination;
import com.che.libcommon.ui.LazyFragment;
import com.qq.e.ads.nativ.ADSize;
import com.qq.e.ads.nativ.NativeExpressAD;
import com.qq.e.ads.nativ.NativeExpressADView;
import com.qq.e.comm.util.AdError;
import com.wswy.wzcx.R;
import com.wswy.wzcx.model.AdModel;
import com.wswy.wzcx.model.news.NewsCategory;
import com.wswy.wzcx.model.news.NewsModel;
import com.wswy.wzcx.module.GlobalConfigManager;
import com.wswy.wzcx.module.ad.AdConfigLoader;
import com.wswy.wzcx.ui.adapter.NewsAdapter3;
import java.util.HashMap;
import java.util.List;
import timber.log.Timber;

public class HomeNewsFragment extends LazyFragment implements INewsView {

  private static final String TAG = "HomeNewsFragment";
  public static final int AD_COUNT = 10;    // 加载广告的条数，取值范围为[1, 10]
  private static final int FIRST_AD_POSITION = 3; // 第一条广告的位置
  public static int ITEMS_PER_AD = 4;     // 每间隔10个条目插入一条广告


  public static HomeNewsFragment newInstance(NewsCategory category){
    return newInstance(category,null);
  }

  public static HomeNewsFragment newInstance(NewsCategory category,int firstAdPos){
    return newInstance(category,null,firstAdPos);
  }

  public static HomeNewsFragment newInstance(NewsCategory category,String statType){
    return newInstance(category,statType,FIRST_AD_POSITION);
  }

  public static HomeNewsFragment newInstance(NewsCategory category,String statType,int firstAdPosition){
    HomeNewsFragment fragment = new HomeNewsFragment();
    Bundle bundle = new Bundle();
    bundle.putParcelable("data",category);
    bundle.putInt("firstAdPosition",firstAdPosition);
    bundle.putString("statType",statType);
    fragment.setArguments(bundle);
    return fragment;
  }


  private RecyclerView recyclerView;

  private View loadingLayout;

  private NewsAdapter3 newAdapter;

  private int firstAdPos = FIRST_AD_POSITION;


  private List<NativeExpressADView> mAdViewList;
  private HashMap<NativeExpressADView, Integer> mAdViewPositionMap = new HashMap<>();


  private FeedAdController mFeedAdController;

  private HomeNewsPresenter mPresenter;

  RVOnScrollListener rvOnScrollListener;

  @Override
  protected int getLayoutId() {
    return R.layout.layout_recuclerview;
  }

  @Override
  protected void initViews(View view, @Nullable Bundle savedInstanceState) {
    super.initViews(view, savedInstanceState);
    recyclerView = view.findViewById(R.id.recycler_view);
    loadingLayout = view.findViewById(R.id.ll_news_loading);
    recyclerView.setLayoutManager(new LinearLayoutManager(view.getContext()));


    recyclerView.addOnScrollListener(new OnScrollListener() {
      @Override
      public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);

        if (rvOnScrollListener != null){
          rvOnScrollListener.onScrollStateChanged(newState);
        }

      }
    });

  }

  @Override
  protected void lazyLoad() {
    String type="";
    String statType = null;
    Bundle arguments = getArguments();
    if (arguments != null){
      NewsCategory category = arguments.getParcelable("data");
      if (category != null){
        type = category.type;
      }
      statType = arguments.getString("statType",null);
      firstAdPos = arguments.getInt("firstAdPosition",FIRST_AD_POSITION);
    }

    mPresenter = new HomeNewsPresenter(getContext(),this,type);

    if (newAdapter == null){
      newAdapter = new NewsAdapter3(((Pagination) mPresenter.loadNews()),type,statType);
    }


    newAdapter.setAdViewPositionMap(mAdViewPositionMap);

    if (recyclerView != null){
      recyclerView.setAdapter(newAdapter);
    }


    Context context = getContext();
    if (context != null && mFeedAdController == null){
      mFeedAdController = new FeedAdController(context,newAdapter,firstAdPos);
    }

  }


  public void reload(){
    //lazyLoad();

    if (mPresenter != null){

      releaseAds();

      if (newAdapter != null){
        newAdapter.setPagination(null);
      }

      Pagination p =(Pagination) mPresenter.reload();
      newAdapter.setPagination(p);
    }

  }


  @Override
  public void showNews(List<NewsModel> list) {

    loadingLayout.setVisibility(View.GONE);
    recyclerView.setVisibility(View.VISIBLE);
    Object t1 = list;

    newAdapter.setNewData(((List) t1));

    newAdapter.notifyDataSetChanged();

    AdModel newsAdModel = GlobalConfigManager.getInstance().getAdsConf().getNewsAdModel();

    if (newsAdModel != null){
      if (TextUtils.equals(newsAdModel.type,AdModel.GDT)){
        initAd();
      }else if (TextUtils.equals(newsAdModel.type,AdModel.TTAD)){
        mFeedAdController.loadAd();
      }
    }


  }

  @Override
  public void showAddNews(List<NewsModel> list) {

    loadingLayout.setVisibility(View.GONE);
    recyclerView.setVisibility(View.VISIBLE);


    Object t = list;

    newAdapter.addData(((List) t));

    newAdapter.notifyDataSetChanged();
    //showAdNextPage();
  }


  private void initAd() {
    ADSize adSize = new ADSize(ADSize.FULL_WIDTH, ADSize.AUTO_HEIGHT); // 消息流中用AUTO_HEIGHT


    NativeExpressAD.NativeExpressADListener listener = new NativeExpressAD.NativeExpressADListener() {
      @Override
      public void onNoAD(AdError adError) {
        Timber.d("onNoAD, error code: %d, error msg: %s", adError.getErrorCode(),
            adError.getErrorMsg());

      }

      @Override
      public void onADLoaded(List<NativeExpressADView> adList) {
        Timber.d("onADLoaded: " + adList.size());

        mAdViewList = adList;
        for (int i = 0; i < mAdViewList.size(); i++) {
          int position = firstAdPos + ITEMS_PER_AD * i;
          if (position < newAdapter.getItemCount()) {
            mAdViewPositionMap.put(mAdViewList.get(i), position); // 把每个广告在列表中位置记录下来
            newAdapter.addADViewToPosition(position, mAdViewList.get(i));
          }
        }
        newAdapter.notifyDataSetChanged();
      }

      @Override
      public void onRenderFail(NativeExpressADView adView) {
        Timber.e("onRenderFail: " );

      }

      @Override
      public void onRenderSuccess(NativeExpressADView adView) {
        Timber.d("onRenderSuccess: " + adView.toString());

      }

      @Override
      public void onADExposure(NativeExpressADView adView) {
        Timber.d("onADExposure");

      }

      @Override
      public void onADClicked(NativeExpressADView adView) {
        Timber.d("onADClicked "+ adView.toString());

      }

      @Override
      public void onADClosed(NativeExpressADView adView) {
        Timber.d("onADClosed: " + adView.toString());
        if (newAdapter != null) {
          int removedPosition = mAdViewPositionMap.get(adView);
          newAdapter.removeADView(removedPosition, adView);
        }
      }

      @Override
      public void onADLeftApplication(NativeExpressADView adView) {

        Timber.d("onADLeftApplication:" );

      }

      @Override
      public void onADOpenOverlay(NativeExpressADView adView) {

        Timber.d("onADOpenOverlay: ");
      }

      @Override
      public void onADCloseOverlay(NativeExpressADView nativeExpressADView) {
        Timber.d("onADCloseOverlay");

      }
    };
    NativeExpressAD mADManager = new NativeExpressAD(getContext(), adSize,
        AdConfigLoader.getGdtConfig().getAppId(),
        AdConfigLoader.getGdtConfig().getFeedId()/*Configs.GDT_HOME_AD_01_ID*/, listener);

    mADManager.loadAD(AD_COUNT);
  }


  private void showAdNextPage() {
    int adSize = mAdViewList == null ? 0 : mAdViewList.size();
    int showSize = mAdViewPositionMap.size();
    if (showSize < adSize && showSize > 0) {
      int j = 0;
      NativeExpressADView lastShowAd = mAdViewList.get(showSize - 1);
      int lastPosition = mAdViewPositionMap.get(lastShowAd);
      for (int i = showSize; i < adSize; i++) {
        NativeExpressADView adView = mAdViewList.get(i);
        int position = lastPosition + ITEMS_PER_AD * ++j;
        if (position < newAdapter.getItemCount()) {
          mAdViewPositionMap.put(adView, position);
          newAdapter.addADViewToPosition(position, adView);
        }
      }
      newAdapter.notifyDataSetChanged();

    }
  }




  private void releaseAds(){
    mAdViewPositionMap.clear();

    if (mAdViewList != null) {
      for (NativeExpressADView view : mAdViewList) {
        view.destroy();
      }

      mAdViewList.clear();
    }
  }


  @Override
  public void onDestroy() {
    super.onDestroy();

   releaseAds();
  }

  @Override
  public boolean rvCanScroll() {

    return recyclerView.getVisibility() == View.VISIBLE &&
        recyclerView.computeVerticalScrollOffset() > 0;
  }


  interface RVOnScrollListener{
    void onScrollStateChanged(int newState);
  }

}
